package com.hdjk.view.activity.main;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lst.projectlib.base.BaseActivity;
import com.lst.projectlib.component.CustomView.TopTitleBar;
import com.hdjk.view.R;

import java.util.Timer;
import java.util.TimerTask;

/**
 * webview页
 */
public class WebBrowseActivity extends BaseActivity implements OnClickListener {
    private TextView navLeft;
    private TextView navTitle;
    private WebView wvBrowse;
    private LinearLayout layReLoad, layLoading;
    private Button btnResfrsh;
    private TextView tvLoaded;
    protected String fixedTitle;//固定标题
    protected String curUrl;// 设置当前访问的url
    private long timeout = 60 * 1000;
    private Timer mTimer;
    private TimerTask tt;
    private Handler mSubHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    // 这里对已经显示出页面且加载超时的情况不做处理
                    if (wvBrowse != null && wvBrowse.getProgress() < 100
                            || wvBrowse.getContentHeight() <= 0) {
                        layLoading.setVisibility(View.GONE);
                        layReLoad.setVisibility(View.VISIBLE);

                        wvBrowse.stopLoading();
                        wvBrowse.clearView();
                        destroyTask();
                    }
                    break;
            }
            return false;
        }
    });

    protected void destroyTask() {
        if (tt != null) {
            tt.cancel();
        }
        if (mTimer != null) {
            mTimer.cancel();
            mTimer.purge();
            mTimer = null;
            tt = null;
        }
    }

    @SuppressLint("NewApi")
    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_web_browse);
        TopTitleBar topTitleBar = (TopTitleBar) findViewById(R.id.topTitleBar);
        navLeft = (TextView) topTitleBar.findViewById(R.id.tvNavBack);
        navLeft.setOnClickListener(this);
        navTitle = (TextView) topTitleBar.findViewById(R.id.tvNavTitle);
        layReLoad = (LinearLayout) findViewById(R.id.layReLoad);
        layLoading = (LinearLayout) findViewById(R.id.layLoading);
        btnResfrsh = (Button) findViewById(R.id.btnResfrsh);
        btnResfrsh.setOnClickListener(this);
        tvLoaded = (TextView) findViewById(R.id.tvLoaded);
        wvBrowse = (WebView) this.findViewById(R.id.wvBrowse);
        wvBrowse.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

        WebSettings setting = wvBrowse.getSettings();
        // 安全考虑
        // 密码不保存,默认会弹出对话框
        setting.setSavePassword(false);

        setting.setSupportZoom(true);//缩放开关
        setting.setBuiltInZoomControls(true);//设置是否可缩放
        setting.setDisplayZoomControls(false);

        //自适应屏幕
        setting.setUseWideViewPort(true);//设置webview推荐使用的窗口，设置为true，无限缩放，就需要使用大视图模式
        setting.setLoadWithOverviewMode(true);//设置webview加载的页面的模式，也设置为true。

        // 设置缓存
//		setting.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        // 取消缓存
        setting.setCacheMode(WebSettings.LOAD_NO_CACHE);

        setting.setAllowFileAccess(true);
        setting.setAppCacheEnabled(true);
        setting.setAllowUniversalAccessFromFileURLs(true);

        // 支持javascript
        setting.setJavaScriptEnabled(true);

        //最重要的方法，一定要设置数据缓存，这就是出不来的主要原因
        setting.setDomStorageEnabled(true);
        //启用数据库
        setting.setDatabaseEnabled(true);

        //启用地理定位
        setting.setGeolocationEnabled(true);
        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        //设置定位的数据库路径
        setting.setGeolocationDatabasePath(dir);

//		//将图片下载阻塞
//		ws.setBlockNetworkImage(true); 

        // 设置WebViewClient
        // 作用:帮助WebView处理各种通知、请求事件,页面跳转，页面请求等操作
        wvBrowse.setWebViewClient(new WebViewClient() {
            private boolean success = true;// 判断此次访问是否正确

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 该方法是对url格式进行修正,并执行读取url地址对应的页面。如果URL地址正确这不执行该方法
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                success = false;

                wvBrowse.stopLoading();
                wvBrowse.clearView();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                if (tt == null) {
                    layLoading.setVisibility(View.VISIBLE);
                    layReLoad.setVisibility(View.GONE);
                    tt = new TimerTask() {
                        protected boolean isGoOn = true;

                        @Override
                        public void run() {
                            if (isGoOn) {
                                Message m = new Message();
                                m.what = 1;
                                mSubHandler.sendMessage(m);
                                mTimer.cancel();
                                mTimer.purge();
                            }

                        }

                        @Override
                        public boolean cancel() {
                            isGoOn = false;
                            return super.cancel();
                        }
                    };
                }
                if (mTimer == null) {
                    mTimer = new Timer();
                    mTimer.schedule(tt, timeout);
                }

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                destroyTask();

                layLoading.setVisibility(View.GONE);
                if (!success) {
                    layReLoad.setVisibility(View.VISIBLE);
                    success = true;// 因为即使页面访问错误，也会执行这个方法所以需要判断
                }
            }
        });

        // 设置WebChromeClient
        // 作用：主要处理关于脚本的执行，辅助WebView处理Javascript的对话框，网站图标，网站title，加载进度等操作
        wvBrowse.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                tvLoaded.setText(newProgress + "%");
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (navTitle != null) {
                    String titleStr = "";
                    if (!TextUtils.isEmpty(fixedTitle)) {
                        titleStr = fixedTitle;
                    } else if (!TextUtils.isEmpty(title)) {
                        titleStr = title.trim();
                    }
                    navTitle.setText(titleStr);
                }
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                return super.onJsConfirm(view, url, message, result);
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
                                      JsPromptResult result) {
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }

        });

        fixedTitle = getIntent().getStringExtra("title");
        curUrl = getIntent().getStringExtra("url");
        wvBrowse.loadUrl(curUrl);
    }

    @Override
    protected void initData() {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvNavBack:
                back();
                break;
            case R.id.tvNavFinish:
                break;
            case R.id.btnResfrsh:
                if (!TextUtils.isEmpty(curUrl)) {
                    wvBrowse.loadUrl(curUrl);
                }
                break;
        }
    }

    //客户端通过以下代码设置cookie
//	private void synCookies(Context context, String url) {
//		String phone=getIntent().getStringExtra("phone");
//		String cookieStr="phone="+phone;
//
//        CookieSyncManager.createInstance(context);
//        CookieManager cookieManager = CookieManager.getInstance();
//        cookieManager.setCookie(url, cookieStr);//第一个参数指定哪一个连接，第2个参数设置的cookie值
//        //cookieManager.setCookie(url, "phone=1243432"+";Max-Age=3600"+";Domain=.163.com"+";Path=/");//cookie相关的信息都存储在第2个参数中
//        CookieSyncManager.getInstance().sync();
//    }

    // 读取cookies的值
//	private void readCookies(){
//		 CookieManager cookieManager = CookieManager.getInstance();
//         String CookieStr = cookieManager.getCookie(curUrl);
//	}

    //客户端可以在注销登录时清除该应用程序用到的所有cookies
//	private void removeCookie(Context context) {
//        CookieSyncManager.createInstance(context);
//        CookieManager cookieManager = CookieManager.getInstance();
//        cookieManager.removeAllCookie();
//        CookieSyncManager.getInstance().sync();
//    }
}